﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Materials;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.MaterialsCommand.QueryMaterialsCommand;
using T.E.ERP.Read.API.Dtos.Dtos;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.MaterialsCommandCommand.QueryMaterialsCommandHandler
{
    /// <summary>
    /// 物料分类的查询命令处理方法
    /// </summary>
    public class MaterialCategoryQueryCommandHandler:IRequestHandler<MaterialCategoryQueryCommand,APIResult<List<MaterialsCopyDto>>>
    {
        /// <summary>
        /// 物料分类仓储接口
        /// </summary>
        private readonly IBaseRepository<MaterialCategoryModel> mRepo;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mRepo"></param>
        /// <param name="mapper"></param>
        public MaterialCategoryQueryCommandHandler(IBaseRepository<MaterialCategoryModel>mRepo,IMapper mapper)
        {
            this.mRepo = mRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIResult<List<MaterialsCopyDto>>> Handle(MaterialCategoryQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MaterialsCopyDto>> result = new APIResult<List<MaterialsCopyDto>>();
            var model = mRepo.GetAll();
            result.Code = APIEnum.成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = GetTree(0);
            return Task.FromResult(result);
        }


        public List<MaterialsCopyDto> GetTree(int id)
        {
            var depars = mRepo.GetAll().Result.Where(x => x.parent_category_id == id);
            var dot = mapper.Map<List<MaterialsCopyDto>>(depars);
            foreach (var item in dot)
            {
                item.children = GetTree(item.id);
            }
            return dot;
        }











    }
}
